package com.le.medium.class3;

import org.junit.Test;

import java.util.Arrays;

/**
 * 给定一个正方形矩阵，只用有限几个变量，实现矩阵中每个位置的数顺时针转动 90度，比如如下的矩阵
 * 0  1  2  3
 * 4  5  6  7
 * 8  9 10 11
 * 12 13 14 15
 * 矩阵应该被调整为：
 * 12  8  4  0
 * 13  9  5  1
 * 14 10  6  2
 * 15 11  7  3
 */
public class Problem04_RotateMatrix {

    public static void rotate(int[][] matrix) {
        int ar = 0;
        int ac = 0;
        int br = matrix.length - 1;
        int bc = matrix[0].length - 1;
        while (ar < br) {
            process(matrix, ar++, ac++, br--, bc--);
        }
    }

    public static void process(int[][] m, int ar, int ac, int br, int bc) {
        int temp = 0;
        for (int i = 0; i < bc - ac; i++) {
            temp = m[ar][ac + i];
            m[ar][ac + i] = m[br - i][ac];
            m[br - i][ac] = m[br][bc - i];
            m[br][bc - i] = m[ar + i][bc];
            m[ar + i][bc] = temp;
        }
    }

    public static void printMatrix(int[][] m){
        for (int i = 0; i < m.length; i++) {
            System.out.println(Arrays.toString(m[i]));
        }
    }

    @Test
    public void test(){
        int[][] matrix = {
                { 0, 1, 2, 3 },
                { 4, 5, 6, 7 },
                { 8, 9, 10, 11 },
                { 12, 13, 14, 15 }
        };
        rotate(matrix);
        printMatrix(matrix);
    }
}
